import 'package:bruno/bruno.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:smart_shop/model/master_worker.dart';
import 'package:smart_shop/page/worker/add.dart';
import 'package:smart_shop/utils/colorUtils.dart';

class Worker extends StatefulWidget {
  const Worker({Key? key}) : super(key: key);

  @override
  State<Worker> createState() => _WorkerState();
}

class _WorkerState extends State<Worker> {
  List<MasterWorker> items = [];

  RefreshController refreshController =
      RefreshController(initialRefresh: false);

  onRefresh() async {
    await Future.delayed(const Duration(milliseconds: 1500));
    refreshController.refreshCompleted();
  }

  @override
  initState() {
    super.initState();
    for (var i = 0; i < 10; i++) {
      items.add(MasterWorker('张三丰', i & 1, 10 + i, '1358978$i'));
    }
  }

  onLoading() async {
    await Future.delayed(const Duration(milliseconds: 1500));
    if (items.length > 100) {
      // 没有数据
      refreshController.loadNoData();
      return;
    }
    items.add(MasterWorker('张三丰', 1, 10, '13589789'));
    if (mounted) {
      setState(() {});
    }
    refreshController.loadComplete();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        localizationsDelegates: const [
          RefreshLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
          GlobalMaterialLocalizations.delegate,
          GlobalCupertinoLocalizations.delegate
        ],
        supportedLocales: const [
          Locale('en'),
          Locale('zh'),
        ],
        locale: const Locale('zh'),
        home: Scaffold(
          appBar: BrnAppBar(
              leading: GestureDetector(
                child: Icon(Icons.arrow_back,
                    color: ColorUtils.fromHex('#212121')),
                onTap: () {
                  Navigator.of(context).pop();
                },
              ),
              automaticallyImplyLeading: false,
              titleAlignment: Alignment.centerLeft,
              title: Container(
                  alignment: Alignment.centerLeft,
                  child: Text('选择服务师傅',
                      style: TextStyle(
                          fontSize: 18,
                          fontFamily: 'Source Han Sans CN',
                          color: ColorUtils.fromHex('#212121'),
                          fontWeight: FontWeight.w500))),
              primary: true,
              backgroundColor: Colors.white),
          body: Padding(
            padding: const EdgeInsets.all(10),
            child: Flex(
              direction: Axis.vertical,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                    flex: 1,
                    child: refreshConfig(
                      child: SmartRefresher(
                        enablePullDown: true,
                        enablePullUp: true,
                        header: const WaterDropHeader(),
                        footer: CustomFooter(
                            builder: (BuildContext context, LoadStatus? mode) {
                          Widget body;
                          if (mode == LoadStatus.idle) {
                            body = const Text('上拉加载');
                          } else if (mode == LoadStatus.loading) {
                            body = const CupertinoActivityIndicator();
                          } else if (mode == LoadStatus.failed) {
                            body = const Text('加载失败！点击重试！');
                          } else if (mode == LoadStatus.canLoading) {
                            body = const Text('松手,加载更多!');
                          } else {
                            body = const Text('没有更多数据了!');
                          }
                          return SizedBox(
                            height: 50,
                            child: Center(child: body),
                          );
                        }),
                        controller: refreshController,
                        onRefresh: onRefresh,
                        onLoading: onLoading,
                        child: ListView.builder(
                          itemBuilder: (c, i) {
                            var item = items[i];
                            return Container(
                              padding: const EdgeInsets.all(10),
                              decoration: const BoxDecoration(
                                  color: Colors.white,
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(6))),
                              child: Column(
                                children: [
                                  Padding(
                                    padding: const EdgeInsets.only(bottom: 8),
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.start,
                                      children: [
                                        Text(item.name,
                                            style: TextStyle(
                                              fontSize: 14,
                                              fontFamily: 'PingFangSC-Regular',
                                              fontWeight: FontWeight.normal,
                                              color:
                                                  ColorUtils.fromHex('#8C8C9A'),
                                            )),
                                        Text(
                                            (item.sex == 1 ? '男' : '女') +
                                                item.count.toString(),
                                            style: TextStyle(
                                              fontSize: 14,
                                              fontFamily: 'PingFangSC-Regular',
                                              fontWeight: FontWeight.normal,
                                              color:
                                                  ColorUtils.fromHex('#8C8C9A'),
                                            ))
                                      ],
                                    ),
                                  ),
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text('接单次数：${item.count}',
                                          style: TextStyle(
                                            fontSize: 14,
                                            fontFamily: 'PingFangSC-Regular',
                                            fontWeight: FontWeight.normal,
                                            color:
                                                ColorUtils.fromHex('#8C8C9A'),
                                          )),
                                      Text(item.mobile,
                                          style: TextStyle(
                                            fontSize: 14,
                                            fontFamily: 'PingFangSC-Regular',
                                            fontWeight: FontWeight.normal,
                                            color:
                                                ColorUtils.fromHex('#8C8C9A'),
                                          ))
                                    ],
                                  )
                                ],
                              ),
                            );
                          },
                          itemExtent: 76,
                          itemCount: items.length,
                        ),
                      ),
                    )),
                Container(
                  height: 68,
                  color: Colors.white,
                  alignment: Alignment.center,
                  child: MaterialButton(
                      onPressed: () {
                        Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                          return const AddWorker();
                        }));
                      },
                      height: 48,
                      minWidth: 153,
                      color: ColorUtils.fromHex('#3D7EFE'),
                      shape: const RoundedRectangleBorder(
                          side: BorderSide.none,
                          borderRadius: BorderRadius.all(Radius.circular(5))),
                      child: const Text(
                        '添加师傅',
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 18,
                            fontWeight: FontWeight.normal,
                            fontFamily: 'PingFangSC-Regular'),
                      )),
                )
              ],
            ),
          ),
        ));
  }

  //基础属性的设置，不多介绍
  Widget refreshConfig({required Widget child}) {
    return RefreshConfiguration(
        headerBuilder: () => const ClassicHeader(
              idleText: "下拉刷新",
              refreshingText: "刷新中...",
              completeText: "加载成功",
              releaseText: "松开立即刷新",
              failedText: '刷新失败',
            ),
        // 配置默认头部指示器,假如你每个页面的头部指示器都一样的话,你需要设置这个，这里设置成比较常见的效果
        footerBuilder: () => const ClassicFooter(
              idleText: "上拉加载",
              loadingText: "加载中…",
              canLoadingText: "松手开始加载数据",
              failedText: "加载失败",
              noDataText: "没有更多数据了",
            ),
        // 配置默认底部指示器
        headerTriggerDistance: 50,
        // 头部触发刷新的越界距离
        footerTriggerDistance: 20,
        //底部触发刷新的越界距离,距离底部多少开始刷新
        springDescription:
            const SpringDescription(stiffness: 170, damping: 16, mass: 1.9),
        //弹性参数，劲度系数、阻尼、质量
        maxOverScrollExtent: 100,
        //头部最大可以拖动的范围,如果发生冲出视图范围区域,请设置这个属性
        maxUnderScrollExtent: 0,
        // 底部最大可以拖动的范围，0默认底部不能往上拖拽
        enableScrollWhenRefreshCompleted: true,
        //这个属性不兼容PageView和TabBarView,如果你特别需要TabBarView左右滑动,你需要把它设置为true
        enableLoadingWhenFailed: true,
        //在加载失败的状态下,用户仍然可以通过手势上拉来触发加载更多
        hideFooterWhenNotFull: false,
        // Viewport不满一屏时,禁用上拉加载更多功能
        enableBallisticLoad: true,
        // 可以通过惯性滑动触发加载更多
        child: child);
  }

  Iterable<LocalizationsDelegate> getLocalizationsDelegates(
      List<LocalizationsDelegate> newDelegates) {
    newDelegates.addAll(GlobalMaterialLocalizations.delegates);
    return newDelegates;
  }
}
